#!/usr/bin/env python
# encoding: utf-8
"""
@author: youfeng
@email: youfeng243@163.com
@license: Apache Licence
@file: shixin_company_list.py
@time: 2018/2/4 20:46
"""

import sys

sys.path.append('../..')
from common import util
from common.mongo import MongDb
from logger import Logger

MONGO_CONF = {
    'host': '172.16.215.16',
    'port': 40042,
    'db': 'app_data',
    'username': 'work',
    'password': 'haizhi'
}
COMPANY_MONGO_DB = {
    'host': '172.16.215.2',
    'port': 40042,
    'db': 'company_data',
    'username': 'work',
    'password': 'haizhi'
}

# 日志模块
log = Logger('shixin_company_list.log').get_logger()

source_db = MongDb(MONGO_CONF['host'], MONGO_CONF['port'], MONGO_CONF['db'],
                   MONGO_CONF['username'],
                   MONGO_CONF['password'], log=log)

target_db = MongDb(COMPANY_MONGO_DB['host'], COMPANY_MONGO_DB['port'], COMPANY_MONGO_DB['db'],
                   COMPANY_MONGO_DB['username'],
                   COMPANY_MONGO_DB['password'], log=log)


def main():
    source_table = 'shixin_info'
    target_table = 'zhejiang_shixin_company_list'
    count = 0
    total = 0
    result_list = []
    for item in source_db.traverse_batch_field(source_table, {}, ['i_name', 'province']):
        total += 1
        i_name = item.get('i_name')
        province = item.get('province')
        if i_name is None or (province != '浙江' and province != u'浙江'):
            continue

        i_name = i_name.strip()
        if i_name == '':
            continue

        if len(i_name) <= 4:
            continue

        data = {
            '_id': i_name,
            '_in_time': util.get_now_time()
        }
        count += 1
        result_list.append(data)
        if len(result_list) >= 1000:
            target_db.insert_batch_data(target_table, result_list)
            del result_list[:]

        if count % 1000 == 0:
            log.info("当前进度: total = {} count = {}".format(total, count))

    if len(result_list) > 0:
        target_db.insert_batch_data(target_table, result_list)
        del result_list[:]

    log.info("查找完成: total = {} count = {}".format(total, count))


if __name__ == '__main__':
    main()
